package com.vhall.autotest.api_test.common;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

public class Http {

	private static final String CHARSET_UTF8 = "utf-8";

	public static void main(String[] args) throws Exception {

		Http http = new Http();
		Map<String, String> param = new HashMap<String, String>();
		param.put("user_id", "785");
		http.post1("http://e.vhall.com/", param);
//		Map<String, String> param = new HashMap<String, String>();
//		param.put("user_id", "785");
//		Map<String, String> result1 = http.get("http://e.vhall.com/", param);
//		System.out.println(result1);
		//
		//
		// Map<String, String> param = new HashMap<String, String>();
		// param.put("user_id", "785");
		// Map<String, String> result2 =
		// http.upload("http://t.vhall.com/user/docupload", "resfile",
		// "E:\\install\\a.txt",
		// param);
		// System.out.println(result2);
		//
		// Map<String, String> param1 = new HashMap<String, String>();
		// Account.setAccount(param1);
		// param1.put("webinar_id", "11");
		// System.out.println("param1:" + param1);
		// Map<String, String> result3 =
		// http.post("http://t.vhall.com/api/vhallapi/v2/webinar/get-online-limit",
		// param1);
		// System.out.println(result3);
		//
		// Map<String, String> param4 = new HashMap<String, String>();
		// param4.put("grant_type", "");
		// param4.put("username", "");
		// param4.put("password", "");
		// param4.put("client_id", "");
		// param4.put("client_secret", "");
		// Map<String, String> result4 =
		// http.post("https://api.jiankongbao.com/v2/", param4);
		// System.out.println(result4);
		//
		// http.ssl("https://api.jiankongbao.com/v2/", param4);
		// Map<String, String> param5 = new HashMap<String, String>();
		// param5.put("id", "848");
		// param5.put("name", "'");
		// param5.put("industry", "<script>alert(document.cookie);</script>");
		// param5.put("email", "'");
		// param5.put("phone", "'\\\\\"");
		// Map<String, String> header5 = new HashMap<String, String>();
		// header5.put("Cookie",
		// "UVISIT=eyJpdiI6Im5XZkVKRjFlelZaa21IeWNDNjVVbGc9PSIsInZhbHVlIjoiU3pkUWFwUVZzMUluaTRwbTdCWURTZz09IiwibWFjIjoiMTJlZDkzZjgwM2RlMGRjNjExNDVjZjMxYzYwZjgyZTMyNzU5ZDFlYjZmZTNlMjVjNDNhNWIxNDY4YjFkN2U5MSJ9;
		// pageGuide=|guideCreate|guideBasicSet|guideEdit|guideZone;
		// trackid=82cb83ba67a036ecc798b02fb73db1d4;
		// looyu_id=b761d3d95c3dda21a49f0a1a5957eaf96c_10036680%3A12;
		// newEntry=|entryCreate;
		// VC=eyJpdiI6InFOQnhlaXZJK1lKeTlGS0ZlVm54Z2c9PSIsInZhbHVlIjoiNTNuQTVYaDQ4NnJyczU1NG5LYlRQbDl0aCtlZ09NcDljcXBwc0duWFhDTT0iLCJtYWMiOiIzMjgwYmUxOTYxY2Y0Mzc5ZWQyNGEzMDQyYWZjOGIzYzIxOTNkMTgwNTQ1OWY4YWQ3OWQ5MTQ2MDJhNmNkYmE3In0%3D;
		// Hm_lvt_2d806e3142b873fd1741af629910957d=1463970023,1463981104,1464166205,1464169374;
		// Hm_lpvt_2d806e3142b873fd1741af629910957d=1464242527;
		// CNZZDATA1253495979=927970526-1460948992-%7C1464242010;
		// laravel_session=eyJpdiI6IjcxN0hxSTRKdnFsdTdiWStwUjVFSVE9PSIsInZhbHVlIjoiKytEc1ZQWkpxcXpRVloydXJJRTYya085ZkdNbkZpMDRoSXp4RmxnUUEyeE1VNjFCZmJRajFtXC91WEx1QUduY2pMRlV0WHB0cUs5R3RVWEt4Znc0bFZRPT0iLCJtYWMiOiI2ZjBmNWU5NzlhZGU1Njg5MDQ3ZjQ4ZDc3ODEyZThmYTc5NDA1OTk2ZTdjMzk2ZWNjNmFiMDM0NjcyNTkxZDFhIn0%3D");
		// String u = "http://t.vhall.com/user/audience/editaudience";
		// Map<String, String> r = http.post(u, param5, header5);
		// System.out.println(r);
		//
		//
//
//		Map<String, String> param6 = new HashMap<String, String>();
//		param6.put("group_id", "259");
//		Map<String, String> result6 = http.upload("http://t.vhall.com/user/audience/excelupload", "resfile",
//				"D:\\用户目录\\下载\\audience (2).xlsx", param6);
//		System.out.println(result6);
		
		
	}

	public void ssl(String url, Map<String, String> param) {
		CloseableHttpClient httpclient = null;
		try {

			org.apache.http.ssl.SSLContextBuilder context_b = SSLContextBuilder.create();
			context_b.loadTrustMaterial(new org.apache.http.conn.ssl.TrustSelfSignedStrategy());
			SSLContext ssl_context = context_b.build();
			org.apache.http.conn.ssl.SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
					ssl_context, new org.apache.http.conn.ssl.DefaultHostnameVerifier());

			HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
			httpclient = builder.build();

			HttpPost post = new HttpPost(url);
			System.out.println("executing request" + post.getRequestLine());
			if (param != null) {
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator(); iterator.hasNext();) {
					Map.Entry<String, String> entry = iterator.next();
					list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "utf-8");
				post.setEntity(uefEntity);
			}
			CloseableHttpResponse response = httpclient.execute(post);
			try {
				HttpEntity entity = response.getEntity();
				System.out.println("—————————————-");
				System.out.println(response.getStatusLine());
				if (entity != null) {
					System.out.println("Response content length: " + entity.getContentLength());
					System.out.println(EntityUtils.toString(entity));
					EntityUtils.consume(entity);
				}
			} finally {
				response.close();
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static Map<String, String> post1(String url, Map<String, String> param, String charset) throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		CloseableHttpClient client = HttpClients.createDefault();
		charset = (charset == null ? CHARSET_UTF8 : charset);
		HttpPost post = new HttpPost(url);
		String paramStr = "";
		if (param != null && param.size() > 0) {
			int i = 0;
			for (Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator(); iterator.hasNext();) {
				Map.Entry<String, String> entry = iterator.next();
				i++;
				paramStr += (entry.getKey() + "=" + entry.getValue() + (i < param.size() ? "&" : ""));
			}
		}
		StringEntity reqEntity = new StringEntity(paramStr);
		reqEntity.setContentType("application/x-www-form-urlencoded");
		post.setEntity(reqEntity);
		CloseableHttpResponse response = client.execute(post);
		try {
			HttpEntity entity = response.getEntity();
			result.put("statusCode", String.valueOf(response.getStatusLine().getStatusCode()));
			if (entity != null) {
				String resultText = new String(EntityUtils.toByteArray(entity), charset);
				result.put("resultText", resultText);
			}
			return result;
		} finally {
			response.close();
		}

	}
	
	public static Map<String, String> post1(String url, Map<String, String> param) throws Exception {
		return post1(url, param, null);
	}

	public Map<String, String> get(String url, Map<String, String> param, String charset, Map<String, String> header)
			throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();
		Map<String, String> result = new HashMap<String, String>();
		charset = (charset == null ? CHARSET_UTF8 : charset);
		try {
			if (param != null && param.size() > 0) {
				url += "?";
				int i = 0;
				for (Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator(); iterator.hasNext();) {
					Map.Entry<String, String> entry = iterator.next();
					i++;
					url += (entry.getKey() + "=" + entry.getValue() + (i < param.size() ? "&" : ""));
				}
			}
			HttpGet get = new HttpGet(url);
			setHeader(get, header);
			System.out.println("executing request " + get.getRequestLine());
			CloseableHttpResponse response = client.execute(get);
			try {
				HttpEntity entity = response.getEntity();
				result.put("statusCode", String.valueOf(response.getStatusLine().getStatusCode()));
				if (entity != null) {
					String resultText = new String(EntityUtils.toByteArray(entity), charset);
					result.put("resultText", resultText);
				}
				return result;
			} finally {
				response.close();
			}
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public Map<String, String> get(String url) throws Exception {
		return get(url, null, null, null);
	}

	public Map<String, String> get(String url, Map<String, String> param) throws Exception {
		return get(url, param, null, null);
	}

	public Map<String, String> get(String url, Map<String, String> param, Map<String, String> header) throws Exception {
		return get(url, param, null, header);
	}

	public Map<String, String> upload(String url, String fileKey, String filePath, String charset,
			Map<String, String> param, Map<String, String> header) throws Exception {
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		Map<String, String> result = new HashMap<String, String>();
		charset = (charset == null ? CHARSET_UTF8 : charset);
		try {
			HttpPost post = new HttpPost(url);
			setHeader(post, header);
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			builder.setCharset(Charset.forName(charset));
			builder.setContentType(ContentType.MULTIPART_FORM_DATA);
			builder.addBinaryBody(fileKey, new File(filePath));
			if (param != null) {
				for (Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator(); iterator.hasNext();) {
					Map.Entry<String, String> entry = iterator.next();
					builder.addTextBody(entry.getKey(), entry.getValue());
				}
			}

			post.setEntity(builder.build());
			System.out.println("executing upload request " + post.getRequestLine());
			response = client.execute(post);
			result.put("statusCode", String.valueOf(response.getStatusLine().getStatusCode()));
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				String resultText = new String(EntityUtils.toByteArray(resEntity), charset);
				result.put("resultText", resultText);
			}
			EntityUtils.consume(resEntity);
			return result;
		} finally {
			if (response != null) {
				response.close();
			}
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public Map<String, String> upload(String url, String fileKey, String filePath, Map<String, String> param)
			throws Exception {
		return upload(url, fileKey, filePath, null, param, null);
	}

	public Map<String, String> upload(String url, String fileKey, String filePath, Map<String, String> param,
			Map<String, String> header) throws Exception {
		return upload(url, fileKey, filePath, null, param, header);
	}

	public Map<String, String> post(String url, Map<String, String> param, String charset, Map<String, String> header, String contentType)
			throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		Map<String, String> result = new HashMap<String, String>();
		HttpPost post = new HttpPost(url);
		setHeader(post, header);
		charset = (charset == null ? CHARSET_UTF8 : charset);
		CloseableHttpResponse response = null;
		try {
			if (param != null) {
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (Iterator<Map.Entry<String, String>> iterator = param.entrySet().iterator(); iterator.hasNext();) {
					Map.Entry<String, String> entry = iterator.next();
					list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, charset);
				if(contentType != null){
					uefEntity.setContentType(contentType);
				}
				post.setEntity(uefEntity);
			}
			System.out.println("executing request " + post.getRequestLine());
			response = httpclient.execute(post);
			result.put("statusCode", String.valueOf(response.getStatusLine().getStatusCode()));
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String resultText = new String(EntityUtils.toByteArray(entity), charset);
				result.put("resultText", resultText);
			}
			return result;
		} finally {
			if (response != null) {
				response.close();
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public Map<String, String> post(String url, Map<String, String> param, Map<String, String> header)
			throws Exception {
		return post(url, param, null, header, null);
	}

	public Map<String, String> post(String url, Map<String, String> param) throws Exception {
		return post(url, param, null, null, null);
	}
	
	public Map<String, String> post(String url, Map<String, String> param, String contentType) throws Exception {
		return post(url, param, null, null, contentType);
	}

	private void setHeader(HttpPost post, Map<String, String> header) {
		if (header != null && post != null) {
			for (Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator(); iterator.hasNext();) {
				Map.Entry<String, String> entry = iterator.next();
				post.addHeader(entry.getKey(), entry.getValue());
			}
		}
	}

	private void setHeader(HttpGet get, Map<String, String> header) {
		if (header != null && get != null) {
			for (Iterator<Map.Entry<String, String>> iterator = header.entrySet().iterator(); iterator.hasNext();) {
				Map.Entry<String, String> entry = iterator.next();
				get.addHeader(entry.getKey(), entry.getValue());
			}
		}
	}
}
